<template>
  <!-- 头部信息 -->
  <HeaderView title="图书兄弟" :hasBack='false' path=""/>

  <!-- banner和swiper -->
  <div class="bannerSwiper" v-if="bannerData.length !== 0" ref="bannerSwiperRef">
    <BannerView :swiperData="swiperData"/>
    <SwiperView :swiperData="swiperData"/>
  </div>

  <!-- tab选项卡 -->
  <TabView v-if="bannerData.length !== 0"/>

  <!-- 底部tabbar -->
  <BottomView/>

  <!-- 时间超时 -->
  <TimeOutView v-if="timeFlag"/>

  <!-- 返回顶部 -->
  <van-icon name="upgrade" class="back" v-show="backTop" @click="goTop"/>
</template>

<script lang="ts" setup>
import HeaderView from '@/components/Header/IndexView.vue'
import BannerView from './component/BannerView.vue'
import SwiperView from './component/SwiperView.vue'
import BottomView from '@/components/Bottom/IndexView.vue'
import TimeOutView from '@/components/TimeOut/IndexView.vue'
import TabView from './component/TabView.vue'

import { GetHomeData } from '@/api/home'
import { onMounted, ref, onActivated, onDeactivated } from 'vue'

const loading = ref(true)
const bannerData = ref([])
const swiperData = ref([])
const timeFlag = ref(false) // 请求超时 显示界面
const bannerSwiperRef = ref<any>(null)
const bannerSwiperHeight = ref(0) // banner和swiper加起来的高度
const scrollHeight = ref(0) // 页面滚动的高度
const backTop = ref(false) // 返回顶部图片

onMounted(() => {
  init()
  window.addEventListener('scroll', handleScroll)
})

// banner swiper数据初始化
const init = async () => {
  const res = await GetHomeData().catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') timeFlag.value = true
  })

  try {
    if (res?.status === 200) {
      loading.value = false
      bannerData.value = res.data.slides // banner数据
      swiperData.value = res.data.goods.data // swiper数据
    }
  } catch (error) {
    console.log(error)
  }
}

// 滚动页面 固定tab 显示回到顶部
const handleScroll = () => {
  try {
    bannerSwiperHeight.value = bannerSwiperRef?.value.offsetHeight
    scrollHeight.value = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    const tabTitle = document.getElementsByClassName('van-tabs__wrap')

    // 滚动的距离 > banner和Swiper高度的总和
    if (scrollHeight.value > bannerSwiperHeight.value) {
      backTop.value = true
      // 固定tab
      tabTitle[0].setAttribute('style', 'width: 100%; position: fixed; top: 46px; left: 0; z-index: 100; background: #fff')
    } else {
      backTop.value = false
      tabTitle[0].removeAttribute('style')
    }
  } catch (error) {
    console.log(error)
  }
}

// 返回顶部
const goTop = () => {
  window.scrollTo(0, 0)
}

// 缓存激活事件
onActivated(() => {
  window.scrollTo(0, scrollHeight.value)
  window.addEventListener('scroll', handleScroll)
})

// 缓存失去事件
onDeactivated(() => {
  window.removeEventListener('scroll', handleScroll)
})

</script>
<script lang="ts">
export default {
  name: 'homeView'
}
</script>

<style lang="scss" scoped>
.back{
  position: fixed;
  bottom:120px;
  right:10px;
  font-size: 30px;
  z-index: 10;
}
</style>
